package com.qf.common.mp.config;


import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ReturnedMessage;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

@Component
@Slf4j
public class CustomRabbitMqCallback implements RabbitTemplate.ConfirmCallback, RabbitTemplate.ReturnsCallback {
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @PostConstruct
    public void init() {
        // mandatory：交换机无法根据自身类型和路由键找到一个符合条件的队列时的处理方式
        // true：将消息返回给生产者
        // false：把消息直接丢弃
        rabbitTemplate.setMandatory(true);
        //指定 ConfirmCallback
        rabbitTemplate.setConfirmCallback(this);
        //指定 ReturnsCallback
        rabbitTemplate.setReturnsCallback(this);
    }

    // 交换机接收到消息就会执行ConfirmCallback中的confirm方法
    @Override
    public void confirm(CorrelationData correlationData, boolean isSendSuccess, String error) {
        String id = correlationData != null ? correlationData.getId() : "";
        if (isSendSuccess) {
            log.info("发送消息到交换机成功, id:{}", id);
        } else {
            log.error("发送消息到交换器失败, id:{}, cause:{}", id, error);
        }
    }

    // 如果消息未能达到指定队列，将调用ReturnsCallback的returnedMessage的方法
    @Override
    public void returnedMessage(ReturnedMessage returnedMessage) {
        String exchange = returnedMessage.getExchange();
        String routingKey = returnedMessage.getRoutingKey();

        log.info("消息被退回，msg:{}, replyCode:{}. replyText:{}, exchange:{}, routingKey :{}",
                returnedMessage.getMessage(), returnedMessage.getReplyCode(), returnedMessage.getReplyText(),
                exchange, returnedMessage.getRoutingKey());
    }
}
